package com.strive.village.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.strive.village.entity.TbResident;
import com.strive.village.entity.dto.ResidentDto;
import com.strive.village.exception.EasyExcelException;
import com.strive.village.mapper.TbVillageMapper;
import com.strive.village.service.TbResidentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 文件导入类
 *
 * @description： 问价导入数据库
 * @author：StrivePeng
 */
@Component
public class DBResidentUploadUtils implements ReadListener<ResidentDto> {

    // 分批导入数据库 缓存信息
    private final List<TbResident> residentList = new ArrayList<>();

    @Autowired
    TbVillageMapper villageMapper;

    @Autowired
    TbResidentService residentService;

    /**
     * 读入一行数据后需要进行什么操作
     *
     * @param residentDto     将数据读出到dto类中
     * @param analysisContext 读取的内容
     */
    @Override
    public void invoke(ResidentDto residentDto, AnalysisContext analysisContext) {
        if (analysisContext != null) {
            TbResident tbResident = new TbResident();
            tbResident.setName(residentDto.getName());
            tbResident.setAge(residentDto.getAge());
            tbResident.setGender(residentDto.getGender());
            tbResident.setOccupation(residentDto.getOccupation());
            tbResident.setContactNumber(residentDto.getContactNumber());

            // 根据乡村名查找ID
            String villageName = residentDto.getVillageName();
            int villageId = villageMapper.getIdByVillageName(villageName);
            tbResident.setVillageId(villageId);

            // 添加到缓存
            residentList.add(tbResident);
            // 分批处理
            if (residentList.size() >= 100) {
                residentService.saveBatch(residentList);
                residentList.clear();
            }
        } else {
            throw new EasyExcelException("文件为空");
        }
    }

    /**
     * 数据读取完毕要执行的操作
     *
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 保存最后的信息
        residentService.saveBatch(residentList);
        residentList.clear();
    }
}
